"""
房间相关模型
"""
from sqlalchemy import Column, Integer, String, Text, DateTime, DECIMAL, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime
from extension import db


class RoomType(db.Model):
    """房间类型表"""
    __tablename__ = 'room_types'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False, comment='类型名称')
    description = Column(Text, comment='类型描述')
    base_price = Column(DECIMAL(10, 2), nullable=False, comment='基础价格')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    rooms = relationship('Room', back_populates='room_type', lazy=True)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'base_price': float(self.base_price) if self.base_price else 0.0,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建实例"""
        return cls(
            name=data.get('name'),
            description=data.get('description'),
            base_price=data.get('base_price', 0)
        )


class RoomStatus(db.Model):
    """房间状态表"""
    __tablename__ = 'room_status'
    id = Column(Integer, primary_key=True)
    name = Column(String(20), nullable=False, comment='状态名称')
    color_code = Column(String(20), comment='状态显示颜色')
    description = Column(Text, comment='状态描述')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    rooms = relationship('Room', back_populates='room_status', lazy=True)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'color_code': self.color_code,
            'description': self.description,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建实例"""
        return cls(
            name=data.get('name'),
            color_code=data.get('color_code'),
            description=data.get('description')
        )


class Room(db.Model):
    """房间表"""
    __tablename__ = 'rooms'
    id = Column(Integer, primary_key=True)
    room_number = Column(String(10), nullable=False, unique=True, comment='房间号')
    floor = Column(Integer, nullable=False, comment='楼层')
    room_type_id = Column(Integer, ForeignKey('room_types.id'), nullable=False, comment='房间类型')
    room_status_id = Column(Integer, ForeignKey('room_status.id'), nullable=False, default=1, comment='房间状态')
    area = Column(Integer, comment='面积(m²)')
    bed_type = Column(String(20), comment='床型')
    max_guests = Column(Integer, comment='最大入住人数')
    description = Column(Text, comment='房间描述')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 定义关系
    room_type = relationship('RoomType', back_populates='rooms')
    room_status = relationship('RoomStatus', back_populates='rooms')
    reservations = relationship('Reservation', back_populates='room', lazy=True)
    
    def to_dict(self, include_relations=True):
        """转换为字典"""
        result = {
            'id': self.id,
            'room_number': self.room_number,
            'floor': self.floor,
            'room_type_id': self.room_type_id,
            'room_status_id': self.room_status_id,
            'area': self.area,
            'bed_type': self.bed_type,
            'max_guests': self.max_guests,
            'description': self.description,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
        
        # 如果包含关联对象，添加关联数据
        if include_relations:
            if self.room_type:
                result['room_type'] = self.room_type.to_dict()
            if self.room_status:
                result['room_status'] = self.room_status.to_dict()
        
        return result
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建实例"""
        return cls(
            room_number=data.get('room_number'),
            floor=data.get('floor'),
            room_type_id=data.get('room_type_id'),
            room_status_id=data.get('room_status_id', 1),
            area=data.get('area'),
            bed_type=data.get('bed_type'),
            max_guests=data.get('max_guests', 2),
            description=data.get('description')
        )
    
    def update_from_dict(self, data):
        """从字典更新实例"""
        if 'room_number' in data:
            self.room_number = data['room_number']
        if 'floor' in data:
            self.floor = data['floor']
        if 'room_type_id' in data:
            self.room_type_id = data['room_type_id']
        if 'room_status_id' in data:
            self.room_status_id = data['room_status_id']
        if 'area' in data:
            self.area = data['area']
        if 'bed_type' in data:
            self.bed_type = data['bed_type']
        if 'max_guests' in data:
            self.max_guests = data['max_guests']
        if 'description' in data:
            self.description = data['description']
        return self

